package com.vecspace.framework.sysdata.dao;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.vecspace.cache.InMemoryCache;
import com.vecspace.data.model.DataLockState;
import com.vecspace.database.dao.AbstractDao;
import com.vecspace.utils.Convert;

@Repository("sys_data_lock_dao")
public class SysDataLockDao extends AbstractDao{

	/**
	 * 
	 * @param tableName 表名
	 * @param schema 表schema，可以为空
	 * @param masterId 父表记录Id；-1表示对本表所有记录的锁定状态。
	 * @param lockTable 被锁定的表，可以为空，表示锁定主表自己
	 * @return
	 * @throws Exception 
	 */
	public int getLockState(Long tableId, Long masterId, String lockTable) throws Exception {
		if(tableId != null && tableId != 0) {
			if(masterId == null) {
				masterId = -1L;//-1L表示对整个表的锁定状态
			}
			if(StringUtils.isBlank(lockTable)) {
				lockTable = "A";
			}
			String sql = "select lock_state from tm_sys_data_lock where table_id=? and data_id=? and lock_name=?";
			Object lockStateObj = dao.queryValue(sql, new Object[]{tableId, masterId, lockTable});
			if(lockStateObj == null)return DataLockState.UNLOCKED;
			int lockState = Convert.toInt(lockStateObj, 0);
			return lockState;
		}else return DataLockState.UNLOCKED;
	}
	
	/**
	 * 
	 * @param tableName 表名
	 * @param schema 表schema，可以为空
	 * @param masterId 父表记录Id；-1表示对本表所有记录的锁定状态。
	 * @param lockTable 被锁定的表，可以为空，表示锁定主表自己
	 * @param lockTable 锁定状态，参考 DataLockState
	 * @return
	 * @throws Exception 
	 */
	public void changeLockState(Long tableId, Long masterId, String lockTable, int lockState) throws Exception {		
		if(tableId != null && tableId != 0) {
			if(masterId == null) {
				masterId = -1L;//-1L表示对整个表的锁定状态
			}
			if(StringUtils.isBlank(lockTable)) {
				lockTable = "A";
			}
			String sql = "update tm_sys_data_lock set lock_state=? where table_id=? and data_id=? and lock_name=?";
			int rcount = dao.updateDataRowBySql(sql, new Object[]{lockState, tableId, masterId, lockTable});
			if(rcount == 0) {
				sql = "insert into tm_sys_data_lock(table_id,data_id,lock_name,lock_state,tenant_id) values(?,?,?,?,?)";
				dao.insertDataRowBySql(sql, new Object[]{tableId, masterId, lockTable, lockState, 1});
			}
		}
	}
	
}
